package com.cu.jiekong.frame;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author jintian
 * @date 14:45
 */
@Component
public class CacheManager {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * redis同步锁
     *
     * @param key        锁住的key
     * @param lockedTime 锁有效时间（单位毫秒）
     * @return
     */
    public boolean lock(String key, long lockedTime) {
        if (redisTemplate.getConnectionFactory().getConnection().setNX(key.getBytes(), "1".getBytes())) {
            redisTemplate.expire(key, lockedTime, TimeUnit.MILLISECONDS);
            return true;
        }
        return false;
    }

    /**
     * 解锁
     *
     * @param key
     */
    public void unlock(String key) {
        redisTemplate.delete(key);
    }

    public void deleteKey(String key) {
        redisTemplate.delete(key);
    }

    public <T> T getValue(String key) {
        return (T) redisTemplate.opsForValue().get("key");
    }

    public void setValue(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void setValue(String key, Object value, long outTime) {
        redisTemplate.opsForValue().set(key, value, outTime);
    }

    public List getListValue(String key, int start, int end) {
        return redisTemplate.opsForList().range(key, start, end);
    }
}
